<template>
  <el-dialog
    :title="headTitle"
    :visible.sync="dialogVisible"
    width="400px"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div class="dialog">
      <div class="dialog-list">
        <label require="true">选择城市:</label>
        <div class="span">
          <el-cascader
            v-model="formData.center"
            :props="props"
            @change="handleChange"
          ></el-cascader>
        </div>
      </div>
      <div class="dialog-list">
        <label require="true">名称:</label>
        <div class="span">
          <el-input size="small" v-model="formData.deptName"></el-input>
        </div>
      </div>
      <div class="dialog-list">
        <label>别名:</label>
        <div class="span">
          <el-input size="small" v-model="formData.deptShortName"></el-input>
        </div>
      </div>
      <div class="dialog-list">
        <label require="true">上级组织:</label>
        <div class="span">
          <el-select
            size="small"
            v-model="formData.parentId"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="item in newtreeData"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="dialog-list">
        <label require="true">组织类型:</label>
        <div class="span">
          <el-select
            size="small"
            v-model="formData.deptType"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="item in newdeptTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="dialog-list">
        <label require="true">组织代码:</label>
        <div class="span">
          <el-input size="small" v-model="formData.deptCode"></el-input>
        </div>
      </div>
      <div class="dialog-list" v-show="formData.deptType == '2'">
        <label require="true">服务项目名称:</label>
        <div class="span">
          <el-input size="small" v-model="formData.serviceName"></el-input>
        </div>
      </div>
      <div class="dialog-list" v-show="formData.deptType == '2'">
        <label require="true">服务项目别名:</label>
        <div class="span">
          <el-input size="small" v-model="formData.serviceShortName"></el-input>
        </div>
      </div>
      <div class="dialog-list" v-show="formData.deptType == '2'">
        <label>项目合同额:</label>
        <div class="span">
          <el-input size="small" v-model="formData.amount"></el-input>
        </div>
      </div>
      <div
        class="dialog-list"
        v-show="formData.deptType == '2' && formData.amount"
      >
        <label></label>
        <div class="span" style="color: red; font-weight: bold">
          {{ numberToUpper(formData.amount) }}
        </div>
      </div>
      <div class="dialog-list" v-show="formData.deptType == '2'">
        <label>项目工期</label>
        <div class="span">
          <!-- <el-date-picker
            v-model="formData.projectDuration"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker> -->
          <el-input
            size="small"
            @input="
              formData.projectDuration = formData.projectDuration.replace(
                /[^\d]/g,
                ''
              )
            "
            v-model="formData.projectDuration"
          ></el-input>
        </div>
      </div>
      <div class="dialog-list">
        <label>是否启用:</label>
        <div class="span">
          <div v-show="formData.status == '0'" class="span-sure">是</div>
          <div v-show="formData.status == '1'" class="span-fou">否</div>
          <el-switch
            size="small"
            v-model="formData.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="0"
            inactive-value="1"
          >
          </el-switch>
        </div>
      </div>
      <!-- <div class="dialog-list">
        <label require="true">组织顺序:</label>
        <div class="span">
          <el-input size="small" v-model="formData.orderNum"></el-input>
        </div>
      </div> -->
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="save">提交</el-button>
      <el-button @click="(dialogVisible = false), updateKey()">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
let id = 0;
import request from "@/utils/request";
import Qs from "qs";
export default {
  props: {
    headTitle: {},
    treeData: {},
  },
  data() {
    return {
      dialogVisible: false,
      newtreeData: [],
      formData: {
        deptName: "",
        deptShortName: "",
        parentId: "",
        deptType: "",
        deptCode: "",
        serviceName: "",
        serviceShortName: "",
        amount: "",
        projectDuration: "",
        orderNum: "2",
        status: "",
        center: [],
      },
      newdeptTypeList: [],
      deptTypeList: [
        {
          value: "1",
          label: "分公司",
        },
        {
          value: "2",
          label: "项目部",
        },
      ],
      dateRange: "",
      // value: "",
      value1: "",
      pData: {},
      city: [],
      props: {
        lazy: true,
        lazyLoad: this.lazyLoad,
      },
    };
  },
  watch: {
    formData: {
      handler(val) {
        if (val.deptType === "1") {
          this.newtreeData = this.treeData.filter(
            (item) => item.parentId === 0
          );
        }
        if (val.deptType === "2") {
          this.newtreeData = this.treeData.filter(
            (item) => item.parentId === 100
          );
        }
        if (!val.deptType || val.deptType === "") {
          this.newtreeData = this.treeData;
        }

        if (val.parentId === 100) {
          this.newdeptTypeList = this.deptTypeList.filter(
            (item) => item.value === "1"
          );
        }
        if (val.parentId !== 100 && val.parentId && val.parentId !== "") {
          this.newdeptTypeList = this.deptTypeList.filter(
            (item) => item.value === "2"
          );
        }
        if (!val.parentId || val.parentId === "") {
          this.newdeptTypeList = this.deptTypeList;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    lazyLoad(node, resolve) {
      console.log(node.data);
      if (node.value) {
        this.allCity(node, resolve, node.data.cityCode);
      } else {
        this.getProvence(node, resolve);
      }
    },
    getProvence(node, resolve) {
      request({
        url: "/system/map/province",
        method: "get",
        data: {},
      }).then((res) => {
        console.log(res);
        const nodes = res.data.map((item) => ({
          value: item.center,
          label: item.name,
          cityCode: item.citycode,
          leaf: node.level >= 1, // 5层级
        }));
        resolve(nodes);
      });
    },
    allCity(node, resolve, cityCode) {
      request({
        url: `/system/map/region?cityCode=${cityCode}`,
        method: "get",
        // headers: { "content-type": "application/x-www-form-urlencoded" },
        // data: Qs.stringify({ cityCode })
      }).then((res) => {
        console.log(res);
        const nodes = res.data.map((item) => ({
          value: item.center,
          label: item.name,
          name1: item.cityCode,
          leaf: node.level >= 0, // 5层级
        }));
        resolve(nodes);
      });
    },
    handleChange(value) {
      console.log(value);
    },
    numberToUpper(money) {
      let prefix = "";
      if (money < 0) {
        prefix = "负";
        money=Math.abs(money)
      }
      var cnNums = new Array(
        "零",
        "壹",
        "贰",
        "叁",
        "肆",
        "伍",
        "陆",
        "柒",
        "捌",
        "玖"
      ); //汉字的数字
      var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
      var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
      var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
      var cnInteger = "整"; //整数金额时后面跟的字符
      var cnIntLast = "元"; //整型完以后的单位
      var maxNum = 999999999999999.9999; //最大处理的数字
      var IntegerNum; //金额整数部分
      var DecimalNum; //金额小数部分
      var ChineseStr = ""; //输出的中文金额字符串
      var parts; //分离金额后用的数组，预定义
      if (money == "") {
        return "";
      }
      money = parseFloat(money);
      if (money >= maxNum) {
        alert("超出最大处理数字");
        return "";
      }
      if (money == 0) {
        ChineseStr = cnNums[0] + cnIntLast + cnInteger;
        return ChineseStr;
      }
      money = money.toString(); //转换为字符串
      if (money.indexOf(".") == -1) {
        IntegerNum = money;
        DecimalNum = "";
      } else {
        parts = money.split(".");
        IntegerNum = parts[0];
        DecimalNum = parts[1].substr(0, 4);
      }
      if (parseInt(IntegerNum, 10) > 0) {
        //获取整型部分转换
        var zeroCount = 0;
        var IntLen = IntegerNum.length;
        for (var i = 0; i < IntLen; i++) {
          var n = IntegerNum.substr(i, 1);
          var p = IntLen - i - 1;
          var q = p / 4;
          var m = p % 4;
          if (n == "0") {
            zeroCount++;
          } else {
            if (zeroCount > 0) {
              ChineseStr += cnNums[0];
            }
            zeroCount = 0; //归零
            ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m == 0 && zeroCount < 4) {
            ChineseStr += cnIntUnits[q];
          }
        }
        ChineseStr += cnIntLast;
        //整型部分处理完毕
      }
      if (DecimalNum != "") {
        //小数部分
        var decLen = DecimalNum.length;
        for (var i = 0; i < decLen; i++) {
          var n = DecimalNum.substr(i, 1);
          if (n != "0") {
            ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      }
      if (ChineseStr == "") {
        ChineseStr += cnNums[0] + cnIntLast + cnInteger;
      } else if (DecimalNum == "") {
        ChineseStr += cnInteger;
      }
      return `${prefix}${ChineseStr}`;
    },
    open(data) {
      this.pData = data;
      if (data.type === "edit") {
        console.log(data.selectData);
        this.formData.deptName = data.selectData.deptName;
        this.formData.deptShortName = data.selectData.deptShortName;
        this.formData.parentId = data.selectData.parentId;
        this.formData.deptType = data.selectData.deptType;
        this.formData.deptCode = data.selectData.deptCode;
        this.formData.serviceName = data.selectData.serviceName;
        this.formData.serviceShortName = data.selectData.serviceShortName;
        this.formData.amount = data.selectData.amount;
        this.formData.projectDuration = data.selectData.projectDuration;
        this.formData.orderNum = data.selectData.orderNum;
        this.formData.deptId = data.selectData.deptId;
        this.formData.status = data.selectData.status;
        if (data.selectData.center) {
          const sp = data.selectData.center.split(",");
          this.formData.center = [`${sp[0]},${sp[1]}`, `${sp[2]},${sp[3]}`];
        } else {
          this.formData.center = [];
        }
      }
      this.dialogVisible = true;
    },
    updateKey() {
      this.$emit("update:keyIndex", new Date().getTime());
    },
    handleClose(done) {
      this.dialogVisible = false;
      this.updateKey();
    },
    save() {
      if (!this.formData.center || this.formData.center.length === 0) {
        this.$message.error("城市不能为空");
        return;
      }
      if (!this.formData.deptName || this.formData.deptName === "") {
        this.$message.error("名称不能为空");
        return;
      }
      if (!this.formData.parentId || this.formData.parentId === "") {
        this.$message.error("上级组织不能为空");
        return;
      }
      if (!this.formData.deptType || this.formData.deptType === "") {
        this.$message.error("组织类型不能为空");
        return;
      }
      if (!this.formData.deptCode || this.formData.deptCode === "") {
        this.$message.error("组织代码不能为空");
        return;
      }
      if (this.formData.deptType == "2") {
        if (!this.formData.serviceName || this.formData.serviceName === "") {
          this.$message.error("服务项目名称不能为空");
          return;
        }
        if (
          !this.formData.serviceShortName ||
          this.formData.serviceShortName === ""
        ) {
          this.$message.error("服务项目别名不能为空");
          return;
        }
      }
      if (!this.formData.orderNum || this.formData.orderNum === "") {
        this.$message.error("组织顺序不能为空");
        return;
      }
      this.formData.center = this.formData.center.join();

      this[this.pData.type]();
    },
    add() {
      request({
        url: "/system/org/add",
        method: "post",
        data: { ...this.formData },
      }).then((res) => {
        this.$emit("reload");
        this.updateKey();
        this.dialogVisible = false;
        console.log(res);
      });
    },
    edit() {
      request({
        url: "/system/org/edit",
        method: "post",
        data: { ...this.formData },
      }).then((res) => {
        this.$emit("reload");
        this.updateKey();
        this.dialogVisible = false;
        console.log(res);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dialog__wrapper {
  .el-dialog__body {
    padding: 0;
  }

  .dialog {
    width: 100%;
    max-height: 400px;
    overflow: auto;
    padding: 10px;

    &-list {
      width: 100%;
      height: 40px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      margin: 10px 0;

      label {
        width: 120px;
        text-align: right;
        padding: 0 10px;
      }

      label[require="true"]::before {
        content: "*";
        color: red;
      }

      .span {
        width: calc(100% - 120px);
        height: 100%;
        display: flex;
        align-items: center;
        position: relative;

        &-sure {
          position: absolute;
          left: 7px;
          top: 13px;
          font-size: 6px;
          font-family: Microsoft YaHei UI;
          font-weight: 400;
          color: #fff;
          z-index: 99;
        }

        &-fou {
          position: absolute;
          left: 22px;
          top: 13px;
          font-size: 6px;
          font-family: Microsoft YaHei UI;
          font-weight: 400;
          color: #ffffff;
          z-index: 99;
        }

        .el-select,
        .el-cascader .el-date-editor {
          width: 100% !important;
        }

        /deep/ .el-cascader {
          width: 220px;
        }
      }
    }
  }
}
</style>
